/*
 * @Author: yangzonglong
 * @Date: 2021-06-30 14:57:27
 * @version: v1.0.0
 * @Descripttion: 上传控件
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-31 10:09:32
 * @Auditor:
 */
import React, { useState, useCallback, useImperativeHandle, forwardRef } from 'react';
import { Toast } from 'antd-mobile';
import RequiredMark from './RequiredMark';
import { uploadIpfs } from '../api';
import DeleteSvg from './imgs/delete.svg';

import styles from './upload.module.scss';

const ComponentUpload = (props, ref) => {
  const [fileList, setFileList] = useState([]);
  const { disabled, uploadProps } = props;

  useImperativeHandle(ref, () => ({
    getData() {
      return fileList;
    },
  }));

  const onChange = useCallback(
    async (e) => {
      if (uploadProps?.maxCount && uploadProps.maxCount === fileList.length - 1) {
        return Toast.info(`总数量不能超过${uploadProps.maxCount}`);
      }

      const _file = document.getElementById('mbfile')?.files?.[0];
      if (uploadProps?.maxSize * 1024 * 1000 < _file.size) {
        // 转成k 对比
        return Toast.info(`不能超过${uploadProps?.maxSize} MB`);
      }
      Toast.loading();
      let formdata = new FormData();
      formdata.append('file', _file);
      const res = await uploadIpfs(formdata);
      setFileList([...fileList, res]);
      Toast.hide();
    },
    [fileList, uploadProps]
  );

  return (
    <div className={styles.side}>
      <div className="am-list-header">
        {
          <span>
            {props?.formItemProps?.required && <RequiredMark />}
            {props?.formItemProps?.label}
          </span>
        }
      </div>
      <div className={styles.div}>
        <button disabled={disabled}>
          <span className={styles.span}>点击上传</span>
        </button>
        <input disabled={disabled} onChange={onChange} type="file" id="mbfile" />
      </div>
      <ul>
        {fileList?.map((item, index) => (
          <li key={item.filename}>
            {item.originalname}
            <img src={DeleteSvg} alt="" onClick={() => setFileList(fileList.filter((ele, i) => i !== index))} />
          </li>
        ))}
      </ul>
    </div>
  );
};

export default forwardRef(ComponentUpload);
